//
//  UIMessageInputView.m
//  Coding_My
//
//  Created by showXxie on 2017/8/31.
//  Copyright © 2017年 sooxie. All rights reserved.
//



#define kKeyboardView_Height 216.0
#define kMessageInputView_Height 50.0
#define kMessageInputView_HeightMax 120.0
#define kMessageInputView_PadingHeight 7.0
#define kMessageInputView_Width_Tool 35.0
#define kMessageInputView_MediaPadding 1.0

#import "UIMessageInputView.h"
#import "UIMessageInputView_Voice.h"
#import "UIPlaceHolderTextView.h"

@interface UIMessageInputView ()<UITextViewDelegate>

@property (assign, nonatomic) CGFloat viewHeightOld;

@property (assign, nonatomic) UIMessageInputViewState inputState;
@property (strong, nonatomic) UIScrollView *contentView;
@property (strong, nonatomic) UIPlaceHolderTextView *inputTextView;


@property (strong, nonatomic) UIButton *addButton, *emotionButton, *photoButton, *voiceButton;


@property (strong, nonatomic) UIMessageInputView_Voice *voiceKeyboardView;
@property (strong, nonatomic) UIView *voiceRedpointView;
@property (strong, nonatomic) UIButton *arrowKeyboardButton;


@end

@implementation UIMessageInputView

#pragma mark 改变frame的时候调用此方法
- (void)setFrame:(CGRect)frame {
    
    //旧值
    CGFloat oldheightToBottom = kScreen_Height - CGRectGetMinY(self.frame);
    //新值
    CGFloat newheightToBottom = kScreen_Height - CGRectGetMinY(frame);
    [super setFrame:frame];
    if (fabs(oldheightToBottom - newheightToBottom) > 0.1) {
        
        if (oldheightToBottom > newheightToBottom) {//降下去的时候保存
            //        [self saveInputStr];
            //        [self saveInputMedia];
        }
        
        if (_delegate && [_delegate respondsToSelector:@selector(messageInputView:heightToBottomChenged:)]) {
            [self.delegate messageInputView:self heightToBottomChenged:newheightToBottom];
        }
        
    }
    
    
    
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = kColorNavBG;
        //        [self addLineUp:YES andDown:NO andColor:kColorCCC];
        
        _viewHeightOld = CGRectGetHeight(frame);
        
        //默认输入状态
        _inputState = UIMessageInputViewStateSystem;
        _isAlwaysShow = NO;
        // _curProject = nil;
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPan:)];
        [self addGestureRecognizer:panGesture];
    }
    return self;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didPan:(UIPanGestureRecognizer *)panGesture
{
    if (panGesture.state == UIGestureRecognizerStateChanged) {
        CGFloat verticalDiff = [panGesture translationInView:self].y;
        if (verticalDiff > 60) {
            [self isAndResignFirstResponder];
        }
    }
}

+ (instancetype)messageInputViewWithType:(UIMessageInputViewContentType)type{
    return [self messageInputViewWithType:type placeHolder:nil];
}


+ (instancetype)messageInputViewWithType:(UIMessageInputViewContentType)type placeHolder:(NSString *)placeHolder{
    
    UIMessageInputView *messageInputView = [[UIMessageInputView alloc] initWithFrame:CGRectMake(0, kScreen_Height, kScreen_Width, kMessageInputView_Height)];
    
    //根据输入的类型自定义ui
    [messageInputView customUIWithType:type];
    
    //    if (placeHolder) {
    //        messageInputView.placeHolder = placeHolder;
    //    }else{
    //        messageInputView.placeHolder = @"撰写评论";
    //    }
    //
    
    return messageInputView;
    
}


#pragma mark - 根据输入类型显示输入框
- (void)customUIWithType:(UIMessageInputViewContentType)type{
    _contentType = type;
    
    CGFloat contentViewHeight = kMessageInputView_Height -2*kMessageInputView_PadingHeight;
    
    NSInteger toolBtnNum;
    BOOL hasEmotionBtn, hasAddBtn, hasPhotoBtn, hasVoiceBtn;
    BOOL showBigEmotion;
    
    
    switch (type) {
        case UIMessageInputViewContentTypePriMsg:
        {
            toolBtnNum = 2;
            hasEmotionBtn = YES;
            hasAddBtn = YES;
            hasPhotoBtn = NO;
            showBigEmotion = YES;
            hasVoiceBtn = YES;
        }
            break;
            
        default:
            
            toolBtnNum = 1;
            hasEmotionBtn = NO;
            hasAddBtn = NO;
            hasPhotoBtn = NO;
            showBigEmotion = NO;
            hasVoiceBtn = NO;
            break;
    }
    
    
    __weak typeof(self) weakSelf = self;
    
    
    if (!_contentView) {
        
        _contentView = [[UIScrollView alloc] init];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.layer.borderWidth = 0.5;
        _contentView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _contentView.layer.cornerRadius = contentViewHeight/2;
        _contentView.layer.masksToBounds = YES;
        _contentView.alwaysBounceVertical = YES;
        [self addSubview:_contentView];
        
        [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            CGFloat left = hasVoiceBtn ? (7+kMessageInputView_Width_Tool+7) : kPaddingLeftWidth;
            make.edges.equalTo(self).insets(UIEdgeInsetsMake(kMessageInputView_PadingHeight, left, kMessageInputView_PadingHeight, kPaddingLeftWidth + toolBtnNum *kMessageInputView_Width_Tool));
        }];
        
        
    }
    
    
    //文字输入
    if (!_inputTextView) {
        _inputTextView = [[UIPlaceHolderTextView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width - kPaddingLeftWidth - toolBtnNum *kMessageInputView_Width_Tool - (hasVoiceBtn ? 7+kMessageInputView_Width_Tool+7 : kPaddingLeftWidth), contentViewHeight)];
        _inputTextView.font = [UIFont systemFontOfSize:16];
        _inputTextView.returnKeyType = UIReturnKeySend;
        _inputTextView.scrollsToTop = NO;
        _inputTextView.delegate = self;
        
        //输入框缩进
        UIEdgeInsets insets = _inputTextView.textContainerInset;
        insets.left += 8.0;
        insets.right += 8.0;
        _inputTextView.textContainerInset = insets;
        
        [self.contentView addSubview:_inputTextView];
    }
    
    
    //设置表情按钮
    if (hasEmotionBtn && !_emotionButton) {
        
        _emotionButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreen_Width - kPaddingLeftWidth/2 - toolBtnNum * kMessageInputView_Width_Tool, (kMessageInputView_Height - kMessageInputView_Width_Tool)/2, kMessageInputView_Width_Tool, kMessageInputView_Width_Tool)];
        
        [_emotionButton setImage:[UIImage imageNamed:@"keyboard_emotion"] forState:UIControlStateNormal];
        //        [_emotionButton addTarget:self action:@selector(emotionButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_emotionButton];
    }
    
    _emotionButton.hidden = !hasEmotionBtn;
    
    
    
    
    //+加按钮
    if (hasAddBtn && !_addButton) {
        _addButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreen_Width - kPaddingLeftWidth/2 -kMessageInputView_Width_Tool, (kMessageInputView_Height - kMessageInputView_Width_Tool)/2, kMessageInputView_Width_Tool, kMessageInputView_Width_Tool)];
        
        [_addButton setImage:[UIImage imageNamed:@"keyboard_add"] forState:UIControlStateNormal];
        //        [_addButton addTarget:self action:@selector(addButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_addButton];
    }
    _addButton.hidden = !hasAddBtn;
    
    
    
    if (hasVoiceBtn && !_voiceButton) {
        
        _voiceButton = [[UIButton alloc] initWithFrame:CGRectMake(7, (kMessageInputView_Height - kMessageInputView_Width_Tool)/2, kMessageInputView_Width_Tool, kMessageInputView_Width_Tool)];
        
        [_voiceButton setImage:[UIImage imageNamed:@"keyboard_voice"] forState:UIControlStateNormal];
        [_voiceButton addTarget:self action:@selector(voiceButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_voiceButton];
        
    }
    _voiceButton.hidden = !hasVoiceBtn;
    
    
    //收起语音键盘按钮
    if (hasVoiceBtn && !_arrowKeyboardButton) {
        _arrowKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _arrowKeyboardButton.frame = CGRectMake(0, 0, kMessageInputView_Width_Tool, kMessageInputView_Width_Tool);
        [_arrowKeyboardButton setImage:[UIImage imageNamed:@"keyboard_arrow_down"] forState:UIControlStateNormal];
        [_arrowKeyboardButton addTarget:self action:@selector(arrowButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_arrowKeyboardButton];
    }
    _arrowKeyboardButton.hidden = YES;
    
    
    //声音输入框
    if (hasVoiceBtn && !_voiceKeyboardView) {
        _voiceKeyboardView = [[UIMessageInputView_Voice alloc] initWithFrame:CGRectMake(0, kScreen_Height, kScreen_Width, kKeyboardView_Height)];
        
        
        _voiceKeyboardView.recordSuccessfully = ^(NSString *file, NSTimeInterval duration){
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(messageInputView:sendVoice:duration:)]) {
                [weakSelf.delegate messageInputView:weakSelf sendVoice:file duration:duration];
            }
        };
        
    }
    
    
    
}



- (void)arrowButtonClicked:(id)sender {
    [self isAndResignFirstResponder];
}

- (BOOL)isAndResignFirstResponder{
    
    if (self.inputState == UIMessageInputViewStateAdd || self.inputState == UIMessageInputViewStateEmotion || self.inputState == UIMessageInputViewStateVoice) {
        
        [UIView animateWithDuration:0.25 delay:0.0f options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
            [_voiceKeyboardView setY:kScreen_Height];
            if (self.isAlwaysShow) {
                [self setY:kScreen_Height- CGRectGetHeight(self.frame)];
            }else{
                [self setY:kScreen_Height];
            }
        } completion:^(BOOL finished) {
            self.inputState = UIMessageInputViewStateSystem;
        }];
        return YES;
        
        
    }else{
        if ([_inputTextView isFirstResponder]) {
            [_inputTextView resignFirstResponder];
            return YES;
        }else{
            return NO;
        }
    }
    
    
}

#pragma makr  - 按钮点击事件

- (void)voiceButtonClicked:(id)sender {
    
    CGFloat endY = kScreen_Height;
    
    
    
    // 更具inputState的set方法改变状态
    if (self.inputState == UIMessageInputViewStateVoice) {
        
        self.inputState = UIMessageInputViewStateSystem;
        [_inputTextView becomeFirstResponder];
    } else {
        
        self.inputState = UIMessageInputViewStateVoice;
        [_inputTextView resignFirstResponder];
        endY = kScreen_Height - kKeyboardView_Height;
    }
    
    
    [UIView animateWithDuration:0.25 delay:0.0f options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        [_voiceKeyboardView setY:endY];
        
        //设置输入框的y
        if (ABS(kScreen_Height - endY) > 0.1) {
            [self setY:endY- CGRectGetHeight(self.frame)];
        }
    } completion:^(BOOL finished) {
        
        
    }];
    
    
    
    
}


#pragma mark - 改变状态
- (void)setInputState:(UIMessageInputViewState)inputState {
    
    if (_inputState != inputState) {
        _inputState = inputState;
        
        switch (_inputState) {
            case UIMessageInputViewStateSystem:
            {
                [self.addButton setImage:[UIImage imageNamed:@"keyboard_add"] forState:UIControlStateNormal];
                [self.emotionButton setImage:[UIImage imageNamed:@"keyboard_emotion"] forState:UIControlStateNormal];
                [self.voiceButton setImage:[UIImage imageNamed:@"keyboard_voice"] forState:UIControlStateNormal];
            }
                break;
            case UIMessageInputViewStateVoice:
            {
                [self.addButton setImage:[UIImage imageNamed:@"keyboard_add"] forState:UIControlStateNormal];
                [self.emotionButton setImage:[UIImage imageNamed:@"keyboard_emotion"] forState:UIControlStateNormal];
                [self.voiceButton setImage:[UIImage imageNamed:@"keyboard_keyboard"] forState:UIControlStateNormal];
            }
                break;
                
            default:
                break;
        }
        
    }
    
    //输入语音时文字输入框隐藏
    _contentView.hidden = _inputState == UIMessageInputViewStateVoice;
    
    _arrowKeyboardButton.hidden = !_contentView.hidden;
    
    _arrowKeyboardButton.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    
    
    [self updateContentViewBecauseOfMedia:NO];
    
}


- (void)updateContentViewBecauseOfMedia:(BOOL)becauseOfMedia{
    
    CGSize textSize = _inputTextView.contentSize, mediaSize = CGSizeZero;
    
    if (!becauseOfMedia) {
        if (ABS(CGRectGetHeight(_inputTextView.frame) - textSize.height) > 0.5) {
            [_inputTextView setHeight:textSize.height];
        }
    }
    
    
}


#pragma mark - 展现输入框
- (void)prepareToShow {
    
    if ([self superview] == kKeyWindow) {
        return;
    }
    [self setY:kScreen_Height];
    [kKeyWindow addSubview:self];
    [kKeyWindow addSubview:_voiceKeyboardView];
    
    if (_isAlwaysShow) {
        [UIView animateWithDuration:0.25 animations:^{
            [self setY:kScreen_Height - CGRectGetHeight(self.frame)];
        }];
    }
    
    //监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
    
    
}


- (void)prepareToDismiss{
    if ([self superview] == nil) {
        return;
    }
    
    [UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        [self setY:kScreen_Height];
    } completion:^(BOOL finished) {
        [_voiceKeyboardView removeFromSuperview];
        [self removeFromSuperview];
    }];
    
}



#pragma mark - textViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if (self.inputState !=
        UIMessageInputViewStateSystem) {
        
        self.inputState = UIMessageInputViewStateSystem;
        
        [UIView animateWithDuration:0.25 delay:0.0f options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
            [_voiceKeyboardView setY:kScreen_Height];
        } completion:^(BOOL finished) {
            self.inputState = UIMessageInputViewStateSystem;
        }];
        
    }
    
    
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    
    if (self.inputState == UIMessageInputViewStateSystem) {
        [UIView animateWithDuration:0.25 delay:0.0f options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
            if (_isAlwaysShow) {
                [self setY:kScreen_Height- CGRectGetHeight(self.frame)];
            }else{
                [self setY:kScreen_Height];
            }
        } completion:^(BOOL finished) {
        }];
    }
    return YES;
}


#pragma mark - KeyBoard Notification Handlers
- (void)keyboardChange:(NSNotification*)aNotification{
    
    if ([aNotification name] == UIKeyboardDidChangeFrameNotification) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil];
    }
    
    if (self.inputState == UIMessageInputViewStateSystem && [self.inputTextView isFirstResponder]) {
        
        NSDictionary* userInfo = [aNotification userInfo];
        
        CGRect keyboardEndFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        
        
        CGFloat keyboardY =  keyboardEndFrame.origin.y;
        
        CGFloat selfOriginY = keyboardY == kScreen_Height? self.isAlwaysShow? kScreen_Height - CGRectGetHeight(self.frame): kScreen_Height : keyboardY - CGRectGetHeight(self.frame);
        
        
        if (selfOriginY == self.frame.origin.y) {
            return;
        }
        
        __weak typeof(self) weakSelf = self;
        void (^endFrameBlock)() = ^(){
            [weakSelf setY:selfOriginY];
        };
        
        
        
        if ([aNotification name] == UIKeyboardWillChangeFrameNotification) {
            
            NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
            
            UIViewAnimationCurve animationCurve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
            
            [UIView animateWithDuration:animationDuration delay:0.0f options:[UIView animationOptionsForCurve:animationCurve] animations:^{
                endFrameBlock();
            } completion:nil];
            
            
            
        }else {
            
            endFrameBlock();
            
        }
        
        
    }
    
    
}


@end
